﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.DosenView
{
    public partial class TugasPage : PhoneApplicationPage
    {
        private DetailMatkul detMatkul;
        private Tugas tugas;

        public TugasPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.DETMATKUL))
            {
                detMatkul = (DetailMatkul)PhoneApplicationService.Current.State[Config.DETMATKUL];
            }
            if (detMatkul == null)
            {
                detMatkul = new DetailMatkul();
                detMatkul.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
            }
            LoadTugas();            
        }

        private void LoadTugas()
        {
            pivotTugas.SelectedIndex = 0;
            listTugas.ItemsSource = null;
            tugas = null;

            string url = string.Format("{0}&{1}", Config.Instance.TUGAS_SERVICE_URL() + Config.VIEW_ACTION_KEY, Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(detMatkul);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listTugas_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void listTugas_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;

            try
            {
                TugasList list = JsonConvert.DeserializeObject<TugasList>(e.Result);
                if (list.Count > 0)
                {
                    listTugas.ItemsSource = list;
                }
                else
                {
                    listTugas.ItemsSource = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void DeleteCurrentTugas()
        {
            string json = null, url = null;

            if (tugas != null)
            {
                url = Config.Instance.TUGAS_SERVICE_URL() + Config.DELETE_ACTION_KEY;
                json = JsonConvert.SerializeObject(tugas);

                Uri uri = new Uri(url, UriKind.Absolute);
                WebClient client = new WebClient();

                client.Encoding = Encoding.UTF8;
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

                client.UploadStringCompleted += new UploadStringCompletedEventHandler(deleteTugas_UploadStringCompleted);

                try
                {
                    client.UploadStringAsync(uri, "POST", json);
                }
                catch (Exception) { }
            }
        }

        private void deleteTugas_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled && e.Error != null)
                    return;

                MessageBox.Show("Message : " + e.Result);
                if (e.Result.Contains("Success"))
                    LoadTugas();

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }
        
        private void listTugas_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                tugas = (Tugas)e.AddedItems[0];
                ((ListBox)sender).SelectedIndex = -1;

                if (tugas != null)
                {
                    pivotTugas.SelectedIndex = 1;
                    textBoxCreated.Text = tugas.Awal.ToString("dd/MM/yyyy");
                    textBoxBatas.Text = tugas.Akhir.ToString("dd/MM/yyyy");
                    textBoxJudul.Text = tugas.Judul;
                    textBoxDeskripsi.Text = tugas.Deskripsi;
                    buttonMhs.IsEnabled = true;
                }
            }
        }

        private void pivotTugas_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tugas == null)
            {
                textBoxCreated.Text = "";
                textBoxJudul.Text = "";
                textBoxDeskripsi.Text = "";
                textBoxBatas.Text = "";
                buttonMhs.IsEnabled = false;
            }

            if (pivotTugas.SelectedIndex == 1 && tugas != null)
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = true;
            }
            else
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = false;
            }
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            Utility.GotoPage(this, "/View/Dosen/TugasFormPage.xaml");

            Tugas task = new Tugas();
            task.DetMatkul = detMatkul;
            PhoneApplicationService.Current.State[Config.TUGAS] = task;
        }

        private void editButton_Click(object sender, EventArgs e)
        {
            Utility.GotoPage(this, "/View/Dosen/TugasFormPage.xaml");

            PhoneApplicationService.Current.State[Config.TUGAS] = tugas;
        }

        private void removeButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Remove " + tugas.Judul + "?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                DeleteCurrentTugas();
            }
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            LoadTugas();
        }

        private void buttonMhs_Click(object sender, RoutedEventArgs e)
        {
            Utility.GotoPage(this, "/View/Dosen/TugasMhsPage.xaml");

            PhoneApplicationService.Current.State[Config.TUGAS] = tugas;
        }

    }
}